package ch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;

/**
 * 只复制SVN提交的文件
 * 
 * @author chen.gang
 * 
 */
public class SVNCopy
{
    public static void main(String[] args) throws IOException
    {
        String root = "E:/work";
        String dest = "C:/Users/Administrator.WIN7U-20130708F/Desktop/test";

        // 清理文件
        File tmp = new File(dest);
        for (File f : tmp.listFiles())
        {
            if (f.isDirectory())
            {
                FileUtils.deleteDirectory(f);
            }
        }

        // 读取SVN日志
        InputStreamReader isr = new InputStreamReader(SVNCopy.class.getResourceAsStream("/changes.txt"));
        BufferedReader bufferedReader = new BufferedReader(isr);

        Set<String> changes = new HashSet<String>();
        String s = null;
        while ((s = bufferedReader.readLine()) != null)
        {
            changes.add(s);
        }

        isr.close();
        bufferedReader.close();

        for (String change : changes)
        {

            // 源文件
            File file = new File(root + change);

            if (file.isDirectory())
            {
                continue;
            }

            if (!file.exists())
            {
                System.err.println("文件[" + file.getAbsolutePath() + "]不存在!");
                continue;
            }

            FileInputStream fileInputStream = new FileInputStream(file);

            // 如果是src下的文件 要拷到web root 下
            String to = change;

            File dstFile = new File(dest + to);

            String dic = dstFile.getParent();

            if (!new File(dic).exists())
            {
                new File(dic).mkdirs();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(dstFile);

            FileChannel readChannel = fileInputStream.getChannel();
            FileChannel writeChannel = fileOutputStream.getChannel();

            readChannel.transferTo(0, readChannel.size(), writeChannel);

            readChannel.close();
            writeChannel.close();

            System.out.println("from [" + file.getAbsolutePath() + "]");
            System.out.println("to   [" + dstFile.getAbsolutePath() + "]");

            System.out.println("-------------------------------");

        }

    }
}
